package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"vote-service/service"
	"connectrpc.com/connect" // 需要取消注释这个导入
	"golang.org/x/net/http2"
	"golang.org/x/net/http2/h2c"
	"github.com/rs/cors" // 使用 rs/cors 包
	"vote-service/gen/vote/voteconnect"
)

func main() {
	// 创建投票服务实例
	voteService := service.NewVoteService()
	
	// 创建 Connect 路由
	mux := http.NewServeMux()
	
	// 创建 CORS 中间件
	corsMiddleware := cors.New(cors.Options{
		AllowedOrigins:   []string{"http://localhost:3000"},
		AllowedMethods:   []string{"GET", "POST", "OPTIONS"},
		AllowedHeaders:   []string{"Content-Type", "Connect-Protocol-Version"},
		AllowCredentials: true,
	})

	// 创建 Connect handler
	path, handler := voteconnect.NewVoteServiceHandler(
		voteService,
		connect.WithCompressMinBytes(1024),
	)
	
	// 应用 CORS 中间件到路由
	mux.Handle(path, corsMiddleware.Handler(handler))

	// 添加健康检查端点
	mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		// 为健康检查也添加 CORS 头
		w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
		w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("OK"))
	})

	// 创建 HTTP 服务器
	server := &http.Server{
		Addr:    ":8080",
		Handler: h2c.NewHandler(mux, &http2.Server{}),
	}

	// 启动服务器
	go func() {
		fmt.Println("投票服务启动在 http://localhost:8080")
		fmt.Println("健康检查: http://localhost:8080/health")
		fmt.Println("Connect 端点: http://localhost:8080" + path)
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("服务器启动失败: %v", err)
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	fmt.Println("正在关闭服务器...")

	// 优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("服务器关闭失败: %v", err)
	}

	fmt.Println("服务器已关闭")
}